package org.example.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.example.handler.UserServerHandler;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    //客户端要远程调用的方法
    public String sayHello(String msg) {

        String s = "RUOK?" + msg;
        System.out.println(s);
        return s;
    }

    //创建一个方法启动服务器
    public static void startServer(String ip, int port) throws InterruptedException {
        //1.创建2个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workerGroup)
                //设置通道类型
                .channel(NioServerSocketChannel.class)
                //创建监听Channel
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    // 事件监听Channel 通道
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = ch.pipeline();
                        //绑定编码
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //把自己的Handller添加到管道中
                        pipeline.addLast(new UserServerHandler());

                    }
                });

        //4.启动引导类绑定端口
        serverBootstrap.bind(ip, port).sync();

        System.out.println("服务器启动");

    }
}
